//
//  DAFileListViewController.m
//  DAKnowledge
//
//  Created by DACadmin on 16/7/7.
//  Copyright © 2016年 lidongyang. All rights reserved.
//

#import "DAFileListViewController.h"
#import "DAHeader.h"
#import "DAUserFileModel.h"
#import "DAFileListTableViewCell.h"
#import "DAWebFileViewController.h"
#import <QuickLook/QuickLook.h>
#import "DAFileSearchTableViewCell.h"
#import "DAUserFileSearchModel.h"
#import "DAFileSearchTableViewCell.h"
#import "DANetWorkReachabilityStatus.h"

@interface DAFileListViewController () <UITableViewDataSource, UITableViewDelegate, UISearchBarDelegate, UISearchDisplayDelegate, UISearchControllerDelegate>{
    UIView *statusCover;
}

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *keys; //存储key值
@property (nonatomic, strong) NSMutableArray *indexArray; //索引数组
@property (nonatomic, strong) NSMutableArray *charactorArray; //A-Z 数组

@property (nonatomic, strong) NSMutableArray *searchResults;
@property (nonatomic, strong) NSMutableArray *collectFiles;

@property (nonatomic, strong) NSMutableDictionary *userDic;
@property (strong, nonatomic) IBOutlet UISearchBar *searchBar;

@property (weak, nonatomic) IBOutlet UIView *searchBarBackView;
@property (strong, nonatomic) IBOutlet UISearchDisplayController *searchDisplayController;

@property (nonatomic, strong) UIView *searchBackView;
@property (nonatomic, strong) DAFileListTableViewCell *tempCell; //for在下载函数里获取到选中Cell

@end

@implementation DAFileListViewController
 int i = 0;
 NSArray *dataArray;
NSArray *tabItems;


- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [SVProgressHUD dismiss];
}
- (void)viewDidLoad {
    [super viewDidLoad];
   // NSLog(@"filenim %@",self.fileNum);
    //如果 没有数据  在页面显示提示消息
    if ([self.fileNum isEqualToString:@"0"]) {
        UIView *backView = [[UIView alloc]init];
        self.tableView.hidden = YES;
        backView.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
        backView.backgroundColor = [UIColor colorWithHexString:backGroundColor];
        [self.view addSubview:backView];
        DALabel *resultLabel = [[DALabel alloc]init];
        resultLabel.numberOfLines = 3;
        resultLabel.frame = CGRectMake(20, self.view.frame.size.height *0.3, self.view.frame.size.width-40, 80);
        NSString *str = NSLocalizedString(@" didn't upload any file", nil);
        NSString *temp = [NSString stringWithFormat:@"%@%@",self.name,str];
        resultLabel.text = temp;
        resultLabel.font = [UIFont fontWithName:@"Helvetica-Bold" size:19];
        resultLabel.textAlignment = NSTextAlignmentCenter;
        resultLabel.textColor = [UIColor colorWithHexString:bookTypeColor];
        [backView addSubview:resultLabel];
    }else{
        self.userDic = [NSMutableDictionary dictionary];
        self.indexArray = [NSMutableArray array];
        [self creatTableView];
        dataArray = [[NSMutableArray alloc]init];
        self.navigationItem.title = self.name;
        // [self creatSearchBackView];
        [self searchSetting];
    //    [self readLocalData];
        [self.tableView.mj_header beginRefreshing];
       // [self prepareCollectFiles];
        self.collectFiles = [[DACollectionFiles shareDACollectionFiles]returnModelArrayInUserID:self.userID];
        // Do any additional setup after loading the view.

    }
    
}

- (void)readLocalData{
    //数据文件保存路径
    NSString *path = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingString:[NSString stringWithFormat:@"%@UploadFile",self.ID]];
    dataArray = [self getLocalDataWithPath:path];
   //dataArray = dic[@"result"];
   // NSLog(@"本地数据 %@",self.userDic);
    [self arraySort];
    [self.tableView reloadData];
    [self.tableView.mj_header endRefreshing];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma mark - 搜索
- (void)searchSetting{
    self.searchBar.backgroundImage = [self imageWithColor:[UIColor colorWithHexString:backGroundColor] size:self.searchBar.bounds.size];
    NSString *search = NSLocalizedString(@"input keywords for searching", nil);
   // NSString *searchKey = [NSString stringWithFormat:@"搜索%@的文件",self.name];
    self.searchBar.placeholder = search;
    self.searchBar.delegate = self;
    self.searchDisplayController.delegate = self;
    UITextField *text = [self.searchBar valueForKey:@"_searchField"];
    [text setValue:[UIFont systemFontOfSize:12] forKeyPath:@"_placeholderLabel.font"];
    self.searchBarBackView.backgroundColor = [UIColor colorWithHexString:backGroundColor];
    
    [self.searchBar setTintColor:[UIColor whiteColor]];
    [[[[self.searchDisplayController.searchBar.subviews objectAtIndex:0] subviews] objectAtIndex:0] removeFromSuperview];
}
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar{
    [self.searchDisplayController.searchBar setBackgroundColor:[UIColor supportGreenColor]];
    statusCover = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREENWIDTH, 20)];
    statusCover.backgroundColor = [UIColor supportGreenColor];
    [self.view addSubview:statusCover];
    [self.searchBar setTintColor:[UIColor whiteColor]];
}
- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar{
    [self.searchDisplayController.searchBar setBackgroundColor:[UIColor colorWithHexString:backGroundColor]];
    [statusCover removeFromSuperview];
    [self.searchBar setTintColor:[UIColor darkGrayColor]];
}
- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(nullable NSString *)searchString{
    [self.searchResults removeAllObjects];
    //    NSPredicate *searchPredicate = [NSPredicate predicateWithFormat:@"self contains[cd] %@", self.searchController.searchBar.text];
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"fileName contains[cd] %@", self.searchBar.text];
    self.searchResults = [[dataArray filteredArrayUsingPredicate:predicate]mutableCopy];
    
    //  [self.tableVIew reloadData];
    [self.searchDisplayController.searchResultsTableView reloadData];
    
    return YES;
}
- (void)searchDisplaycontroller:(UISearchDisplayController *)controller willShowSearchResultsTableView:(UITableView *)tableView{
    [tableView setContentInset:UIEdgeInsetsZero];
    [tableView setScrollIndicatorInsets:UIEdgeInsetsZero];
}
- (void) searchBarCancelButtonClicked:(UISearchBar *)searchBar{
    [self refreshData];
}
- (void)dealloc{
    self.tableView.delegate = nil;
    self.searchBar.delegate = nil;
}
//searchBar  背景色
- (UIImage *)imageWithColor:(UIColor *)color size:(CGSize)size{
    CGRect rect = CGRectMake(0, 20, size.width, size.height);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}
#pragma mark - 索引数组
- (void)arraySort{
    self.keys = [NSMutableArray array];
   // self.indexArray = [NSMutableArray array];
    self.charactorArray = [NSMutableArray array];
    for (char a = '0'; a <= '9'; a++) {
        [self.charactorArray addObject:[NSString stringWithFormat:@"%c",a]];
    }
    for (char a = 'A'; a <= 'Z'; a++) {
        [self.charactorArray addObject:[NSString stringWithFormat:@"%c",a]];
    }
    for (DAUserFileModel *userFileModel in dataArray) {
        NSString *key = [self firstCharactor:userFileModel.fileName];
        [self.keys addObject:key];
    }
    for (NSString *key in self.keys) {
        NSMutableArray *arr = [NSMutableArray array];
        [self.userDic setObject:arr forKey:key];
    }
    for (DAUserFileModel *userFileModel in dataArray) {
        NSString *key = [self firstCharactor:userFileModel.fileName];
        //NSLog(@"file名 %@",userFileModel.fileName);
        [self.userDic[key] addObject:userFileModel];
    }
    self.indexArray = [[self.userDic.allKeys sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)]mutableCopy];
    if ([self.indexArray containsObject:@"#"]) {
        [self.indexArray removeObject:@"#"];
        [self.indexArray addObject:@"#"];
    }
}
// 获取首字母方法
- (NSString *)firstCharactor:(NSString *)string{
    NSMutableString *str = [NSMutableString stringWithString:string];
    CFStringTransform((CFMutableStringRef)str, NULL, kCFStringTransformMandarinLatin, NO);
    CFStringTransform((CFMutableStringRef)str, NULL, kCFStringTransformStripDiacritics, YES);
    NSString *largeStr = [str capitalizedString];
    NSString *firstStr;
    if (string.length != 0) {
        firstStr = [largeStr substringToIndex:1];
    }
    BOOL isContain = [self.charactorArray containsObject:firstStr];
    if (isContain == NO || [firstStr isEqualToString:@""]) {
        firstStr = @"#";
    }
    return firstStr;
}
#pragma mark - 创建搜索框
//- (void)creatSearchBackView{
//    self.searchBackView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 45)];
//    self.searchBackView.backgroundColor = [UIColor colorWithHexString:backGroundColor];
//    self.searchBar = [[UISearchBar alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 44)];
//    [self.searchBackView addSubview:self.searchBar];
//    [self.view addSubview:self.searchBackView];
//                                                                 
//}
#pragma mark - 创建TableView
- (void)creatTableView{
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.tableFooterView = [UIView new];
    [self prepareFileData];
    //[self readLocalData];
    self.tableView.backgroundColor = [UIColor colorWithHexString:backGroundColor];
    self.tableView.sectionIndexColor = [UIColor supportGreenColor];
    self.tableView.sectionIndexBackgroundColor = [UIColor clearColor];
    
    self.tableView.tableHeaderView = self.searchBackView;
    self.searchDisplayController.searchResultsTableView.backgroundColor = [UIColor colorWithHexString:backGroundColor];
    self.searchDisplayController.searchResultsTableView.tableFooterView = [UIView new];
    //
    MJRefreshGifHeader *header =[MJRefreshGifHeader headerWithRefreshingTarget:self refreshingAction:@selector(refreshData)];
    NSMutableArray *refreshImages = [[NSMutableArray alloc] init];
    for (NSUInteger i = 1; i<=21; i++) {
        UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"page%ld@3x", (unsigned long)i]];
        [refreshImages addObject:image];
    }
    NSMutableArray *normalImages = [[NSMutableArray alloc] init];
    for (NSUInteger i = 1; i<=21; i++) {
        UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"stay%ld@3x", (unsigned long)i]];
        [normalImages addObject:image];
    }
    UIImage *image = [UIImage imageNamed:@"stay21@3x"];
    [normalImages insertObject:image atIndex:0];
    
    [header setImages:refreshImages duration:0.5 forState:MJRefreshStateRefreshing];
    [header setImages:normalImages forState:MJRefreshStateIdle];
    [header setImages:refreshImages duration:0.5 forState:MJRefreshStatePulling];
    
    header.lastUpdatedTimeLabel.hidden= YES;//如果不隐藏这个会默认 图片在最左边不是在中间
    header.stateLabel.hidden = YES;
    self.tableView.mj_header = header;
}

- (void)refreshData{
    [self prepareFileData];
    [self readLocalData];
   // [self prepareCollectFiles];
     self.collectFiles = [[DACollectionFiles shareDACollectionFiles]returnModelArrayInUserID:self.userID];
    [self.tableView reloadData];
}

#pragma mark - 用户收藏的文件
- (void)prepareCollectFiles{
    NSString *url = DAUserCollectFiles;
    NSDictionary *dic = @{@"collectUserID":self.userID};
    [DADataHandel postURL:url parame:dic cookie:nil result:^(id result) {
        if ([result[@"result"] isKindOfClass:[NSArray class]] && [result[@"result"] count]>0 ) {
            DAUserFileModel *model = [[DAUserFileModel alloc]init];
            self.collectFiles = [model returnModelInArrayWithDic:result[@"result"]];
        }else{
            if ([result[@"result"] isKindOfClass:[NSString class]] && [result[@"result"] isEqualToString:self.requestTimeOut]) {
                [SVProgressHUD showErrorWithStatus:self.requestTimeOut];
               // [self.tableView.mj_header endRefreshing];
            }
            else if ([result[@"result"] isKindOfClass:[NSString class]] && [result[@"result"] isEqualToString:self.netIsNotAvailabel]) {
                [SVProgressHUD showErrorWithStatus:self.netIsNotAvailabel];
               // [self.tableView.mj_header endRefreshing];
            }
            else if ([result[@"result"] isKindOfClass:[NSString class]] && [result[@"result"] isEqualToString:self.netWorkPortConnection]) {
                [SVProgressHUD showErrorWithStatus:self.netWorkPortConnection];
               // [self.tableView.mj_header endRefreshing];
            }
            else{
                [SVProgressHUD showErrorWithStatus:self.requestFailed];
               // [self.tableView.mj_header endRefreshing];
            }
        }

    }];
}


#pragma mark -  准备数据
- (void)prepareFileData{
    NSString *url = DAUserFileURL;
    NSDictionary *dic = @{@"userID":self.ID};
    //NSLog(@"User ID %@ ",self.ID);
    [self dataHandelWithUrl:url parame:dic];
}

- (void)dataHandelWithUrl:(NSString *)url parame:(NSDictionary *)dic{
    __weak typeof(self) weakSelf = self;
    [DADataHandel postURL:url parame:dic cookie:nil result:^(id result) {
        if ([result[@"result"] isKindOfClass:[NSArray class]] && [result[@"result"] count] > 0){
            [weakSelf archiveToLocalWithData:result];
            [weakSelf dataTransFormModel:result[@"result"]];
            //[weakSelf.tableView.mj_header endRefreshing];
        }else{
            if ([result[@"result"] isKindOfClass:[NSString class]] && [result[@"result"] isEqualToString:self.requestTimeOut]) {
                [SVProgressHUD showErrorWithStatus:self.requestTimeOut];
                 [weakSelf.tableView.mj_header endRefreshing];
            }
            else if ([result[@"result"] isKindOfClass:[NSString class]] && [result[@"result"] isEqualToString:self.netIsNotAvailabel]) {
                [SVProgressHUD showErrorWithStatus:self.netIsNotAvailabel];
                 [weakSelf.tableView.mj_header endRefreshing];
            }
            else if ([result[@"result"] isKindOfClass:[NSString class]] && [result[@"result"] isEqualToString:self.netWorkPortConnection]) {
                [SVProgressHUD showErrorWithStatus:self.netWorkPortConnection];
                 [weakSelf.tableView.mj_header endRefreshing];
            }
            else{
                [SVProgressHUD showErrorWithStatus:self.requestFailed];
                 [weakSelf.tableView.mj_header endRefreshing];
            }
            [self readLocalData];
        }
    }];
}
- (void)dataTransFormModel:(NSArray *)resultArray{
    DAUserFileModel *userFileModel = [[DAUserFileModel alloc]init];
    NSArray *array = [userFileModel returnModelInArrayWithDic:resultArray];
    dataArray = [NSMutableArray array];
    //[dataArray addObjectsFromArray:array];
    [self readLocalData];
    [self arraySort];
   // [self.tableView reloadData];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    if (self.searchDisplayController.active) {
        return 1;
    }else{
        return self.indexArray.count;
    }
}

//索引内容
//- (NSArray<NSString *> *)sectionIndexTitlesForTablcleareView:(UITableView *)tableView{
//    if (tableView == self.tableView ) {
//        return self.indexArray;
//    }else{
//        return nil ;
//    }
//}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    if (tableView == self.tableView ) {
        return [self.indexArray objectAtIndex:section];
    }else{
        return nil;
    }
}

- (NSInteger)tableView:(UITableView*)tableView numberOfRowsInSection:(NSInteger)section{
    if (dataArray != nil && tableView == self.tableView) {
        NSString *key = self.indexArray[section];
        NSArray *arr = [self.userDic objectForKey:key];
        return [arr count];
    }else{
        return [self.searchResults count];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 60;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView == self.tableView ) {
        DAFileListTableViewCell *fileListCell = [tableView dequeueReusableCellWithIdentifier:@"file_Cell"];
        if (fileListCell == nil) {
            fileListCell = [[DAFileListTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"file_Cell"];
        }
        NSString *key = self.indexArray[indexPath.section];
        NSMutableArray *arr = [self.userDic objectForKey:key];
        //CELL属性设置
        DAUserFileModel *model = [arr objectAtIndex:indexPath.row];

//        
        //是否已下载
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDirectory = [paths objectAtIndex:0];
        //NSLog(@"文件保存路径%@",documentsDirectory);
        BOOL isExist = [self isFileExist:[NSString stringWithFormat:@"%@.%@",model.filefolderName,model.fileExtend] inPath:documentsDirectory];
        if (isExist) {
//            // fileListCell.downLoadCompleteImage.image = [UIImage imageNamed:@"complete@3x"];
            model.isDownloadingSuccessful = YES;
//            //[arr replaceObjectAtIndex:indexPath.row withObject:model];
        }
        
        fileListCell.userFileModel = model;

        return fileListCell;
    }else{   //搜索结果Cell
        
        DAFileSearchTableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:@"SearchCell"];
        if (cell == nil) { //需要在storyBoard里新拖一个Cell
            cell = [[DAFileSearchTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"SearchCell"];
        }
        if (self.searchResults.count > 0) {
        cell.userFileSearchModel = self.searchResults[indexPath.row];
        DAUserFileSearchModel *model = [self.searchResults objectAtIndex:indexPath.row];
       
        //判断是否已经下载
            NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
            NSString *documentsDirectory = [path objectAtIndex:0];
            BOOL isExist = [self isFileExist:[NSString stringWithFormat:@"%@.%@",model.filefolderName,model.fileExtend] inPath:documentsDirectory];
            if (isExist) {
                model.isDownloadingSuccessful = YES;
            }
            cell.userFileSearchModel = model;
        //cell.backgroundColor = [UIColor redColor];
    }
        return cell;

    }
}
 
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 20)];
    view.backgroundColor = [UIColor colorWithHexString:backGroundColor];
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(20, 10, 100, 10)];
    label.text = [self.indexArray objectAtIndex:section];
    label.font = [UIFont boldSystemFontOfSize:14];
    label.textColor = [UIColor darkGrayColor];
    [view addSubview:label];
    return view;
}

//Cell左划响应事件
- (NSArray *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *key = self.indexArray[indexPath.section];
    NSMutableArray *arr = [self.userDic objectForKey:key];
    DAUserFileModel *model = [arr objectAtIndex:indexPath.row];
    //DAUserFileModel *temp = [[DAUserFileModel alloc]init];
    DAUserFileModel *trans = [[DAUserFileModel alloc]init];
    BOOL flag = false;
//    for (DAUserFileModel *temp in self.collectFiles){
//        if (model.fileID == temp.fileID) {
//            trans = temp;
//            flag = true;
//            break;
//        }
//    }
//    for (DACollectionFiles *files in self.collectFiles) {
//        files.fileID = model.fileID;
//        flag = true;
//    }
    
    flag = [[DACollectionFiles shareDACollectionFiles] isContainCollectionsWith:model.fileID];
    
    
    if (!flag) {
        //收藏按钮
        UITableViewRowAction *collectRowAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title:@"收藏" handler:^(UITableViewRowAction *_Nonnull action, NSIndexPath * _Nonnull indexPath){
            NSLog(@"收藏");
            NSDictionary *dic;
            NSString *url = DACollectionFile;
            dic = @{@"collectUserID":self.userID , @"collectFolderName":model.filefolderName};
            
            [DADataHandel postURL:url parame:dic cookie:nil result:^(id result) {
                if (result) {
                    NSLog(@"结果 %@",result);
                    //NSLog(@"收藏成功!");
                    [SVProgressHUD showSuccessWithStatus:@"收藏成功"];
                    //[self.collectFiles addObject:model];
                    [[DACollectionFiles shareDACollectionFiles] updateWithUserID:self.userID Block:^(NSMutableArray *array) {
                        self.collectFiles = array;
                    }];
                    if (tableView == self.tableView) {
                    [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
                    }else{
                        [self.searchDisplayController.searchResultsTableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
                    }
                }else{
                   // NSLog(@"收藏失败!");
                    [SVProgressHUD showErrorWithStatus:@"收藏失败"];
                }
            }];
            //NSLog(@"用户 : %@  文件 : %@",self.userID,model.filefolderName);
        }];
        collectRowAction.backgroundColor = [UIColor orangeColor];
        tabItems = [[NSArray alloc]init];
        [tabItems arrayByAddingObject:collectRowAction];
      //  [self prepareCollectFiles];
        return  @[collectRowAction];
    }else{
        //取消收藏按钮
        UITableViewRowAction *collectRowAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title:@"取消收藏" handler:^(UITableViewRowAction *_Nonnull action, NSIndexPath * _Nonnull indexPath){
            NSLog(@"取消收藏");
            NSDictionary *dic;
            NSString *url = DACancelCollectionFile;
            dic = @{@"collectUserID":self.userID , @"collectFolderName":model.filefolderName};

            [DADataHandel postURL:url parame:dic cookie:nil result:^(id result) {
                NSLog(@"结果 %@",result);
                if (result) {
                    //NSLog(@"收藏成功!");
                    [SVProgressHUD showSuccessWithStatus:@"取消收藏成功"];
                    //[self.collectFiles removeObject:trans];
                    [[DACollectionFiles shareDACollectionFiles]updateWithUserID:self.userID Block:^(NSMutableArray *array) {
                        self.collectFiles = array ;
                    }];
                    if (tableView == self.tableView) {
                        [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
                    }else{
                        [self.searchDisplayController.searchResultsTableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
                    }
                }else{
                    NSLog(@"取消收藏失败!");
                    [SVProgressHUD showErrorWithStatus:@"取消收藏失败"];
                }
            }];
        }];
        collectRowAction.backgroundColor = [UIColor orangeColor];
        tabItems = [[NSArray alloc]init];
        [tabItems arrayByAddingObject:collectRowAction];
       // [self prepareCollectFiles];
        return @[collectRowAction];
    }
    //return tabItems;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if(tableView == self.tableView){
        [self.tableView deselectRowAtIndexPath:indexPath animated:YES];
 
        NSString *key = self.indexArray[indexPath.section];
        NSMutableArray *arr = [self.userDic objectForKey:key];
        DAUserFileModel *model = [arr objectAtIndex:indexPath.row];
        DAFileListTableViewCell *cell = [[DAFileListTableViewCell alloc]init] ;
        cell = [self.tableView cellForRowAtIndexPath:indexPath];
        
        //文件保存路径
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDirectory = [paths objectAtIndex:0];
        NSString *filePath = [NSString stringWithFormat:@"%@/%@.%@", documentsDirectory, model.filefolderName,model.fileExtend];
        NSLog(@"文件保存路径 %@",documentsDirectory);
        
        
      //判断文件在本地是否存在
        if(model.isDownloading == YES){
            NSLog(@"正在下载");
        }else{
        
        BOOL isExist = [self isFileExist:[NSString stringWithFormat:@"%@.%@",model.filefolderName,model.fileExtend] inPath:documentsDirectory];
        if (isExist) {
            NSLog(@"文件存在可以直接打开");
            DAWebFileViewController *webFile = [[DAWebFileViewController alloc]init];
            webFile.fileUrl = filePath;
            webFile.fileID = model.fileID;
            webFile.filefolderName = model.filefolderName;
            webFile.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:webFile animated:YES];
        }else{
            //下载文件
            //判断网络连接
            [DANetWorkReachabilityStatus isNetWorkConnectWithBlock:^(BOOL isConnect){
                if (isConnect) {
                    NSLog(@"下载文件");
                    cell.progress.hidden = NO;
                    model.isDownloading = YES;
                    [NSThread detachNewThreadSelector:@selector(downloadFileOnBackground:) toTarget:self withObject:indexPath];
                }else{
                    NSString *str = NSLocalizedString(@"NoNetWorkCouldNotDownload", nil);
                    [SVProgressHUD showErrorWithStatus:str];
                }
            }];
//            if ([DANetWorkReachabilityStatus isNetWorkConnect]) {
//                NSLog(@"下载文件");
//                cell.progress.hidden = NO;
//                model.isDownloading = YES;
//                [arr replaceObjectAtIndex:indexPath.row withObject:model];
//                [self.userDic setValue:arr forKey:key];
//                [NSThread detachNewThreadSelector:@selector(downloadFileOnBackground:) toTarget:self withObject:indexPath];
//            }else{
//                NSLog(@"无网络");
//                NSString *str = NSLocalizedString(@"NoNetWorkCouldNotDownload", nil);
//                [SVProgressHUD showErrorWithStatus:str];
//            }
        }
        }
    }else{  //搜索结果 点击方法
        
        [self.searchDisplayController.searchResultsTableView deselectRowAtIndexPath:indexPath animated:YES];
        
        DAUserFileSearchModel *model = [self.searchResults objectAtIndex:indexPath.row];
        DAFileSearchTableViewCell *cell = [[DAFileSearchTableViewCell alloc]init] ;
        cell = [self.searchDisplayController.searchResultsTableView cellForRowAtIndexPath:indexPath];
        
        //文件保存路径
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDirectory = [paths objectAtIndex:0];
        NSString *filePath = [NSString stringWithFormat:@"%@/%@.%@", documentsDirectory, model.filefolderName,model.fileExtend];
        NSLog(@"文件保存路径 %@",documentsDirectory);
        
        
        //判断文件在本地是否存在
        if(model.isDownloading == YES){
            NSLog(@"正在下载");
        }else{
            
            BOOL isExist = [self isFileExist:[NSString stringWithFormat:@"%@.%@",model.filefolderName,model.fileExtend] inPath:documentsDirectory];
            if (isExist) {
                NSLog(@"文件存在可以直接打开");
                DAWebFileViewController *webFile = [[DAWebFileViewController alloc]init];
                webFile.fileUrl = filePath;
                webFile.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:webFile animated:YES];
            }else{
                //下载文件
                //判断网络连接
                [DANetWorkReachabilityStatus isNetWorkConnectWithBlock:^(BOOL isConnect){
                    if (isConnect) {
                        NSLog(@"下载文件");
                        cell.progress.hidden = NO;
                        model.isDownloading = YES;
                        [NSThread detachNewThreadSelector:@selector(downloadSearchFile:) toTarget:self withObject:indexPath];
                    }else{
                        NSString *str = NSLocalizedString(@"NoNetWorkCouldNotDownload", nil);
                        [SVProgressHUD showErrorWithStatus:str];
                    }
                }];
//                if ([DANetWorkReachabilityStatus isNetWorkConnect]) {
//                    NSLog(@"下载文件");
//                    cell.progress.hidden = NO;
//                    model.isDownloading = YES;
//                    [NSThread detachNewThreadSelector:@selector(downloadSearchFile:) toTarget:self withObject:indexPath];
//                }else{
//                    NSString *str = NSLocalizedString(@"NoNetWorkCouldNotDownload", nil);
//                    [SVProgressHUD showErrorWithStatus:str];
//                }
            }
        }
    }
}

#pragma marks - searchCell下载
- (void)downloadSearchFile:(NSIndexPath *)indexPath{
    DAFileSearchTableViewCell *cell = [[DAFileSearchTableViewCell alloc]init];
    cell = [self.searchDisplayController.searchResultsTableView cellForRowAtIndexPath:indexPath];
//    NSString *key = self.indexArray[indexPath.section];
//    NSArray *arr = [self.userDic objectForKey:key];
    NSLog(@"INDEXPATH是 %@",indexPath);
    DAUserFileSearchModel *model = [self.searchResults objectAtIndex:indexPath.row];
  //  NSLog(@"MODEL %@",model.filefolderName);
    //文件保存路径
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSLog(@"文件保存路径 %@",documentsDirectory);
    
    //文件下载路径
    NSString *str = model.fileUrl;
    NSString *encodedString = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes( kCFAllocatorDefault, (CFStringRef)str, NULL, NULL,  kCFStringEncodingUTF8 ));
    NSURL *url = [NSURL URLWithString:encodedString];
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    NSString  *fullPath = [NSString stringWithFormat:@"%@/%@.%@", documentsDirectory, model.filefolderName,model.fileExtend];
    // NSURL *url = [NSURL URLWithString:@"http://www.abc.com/test.mp4"];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    NSURLSessionDownloadTask *task =
    //    [manager downloadTaskWithRequest:request
    //                            progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
    //                                return [NSURL fileURLWithPath:fullPath];
    //                            }
    //                   completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
    //
    //                   }];
    
    [manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
        
        CGFloat count = 1.0 * downloadProgress.completedUnitCount / downloadProgress.totalUnitCount;
        dispatch_async(dispatch_get_main_queue(), ^{
            [cell.progress setProgress:count animated:YES];
        });
        //  NSLog(@"下载进度 %f",count);
        //    if (self.isFinish == NO) {
        //            [SVProgressHUD  showProgress:count];
        //        }
        
    } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
        return [NSURL fileURLWithPath:fullPath];
    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
        cell.progress.hidden = YES;
        cell.downLoadCompleteImage.image = [UIImage imageNamed:@"complete@3x"];
        model.isDownloading = NO;
        //[SVProgressHUD dismiss];
        // [self creatPreview];
    }];
    [task resume];
    
}

#pragma marks - fileListCell下载
- (void)downloadFileOnBackground:(NSIndexPath *)indexPath{
    DAFileSearchTableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
    NSString *key = self.indexArray[indexPath.section];
    NSArray *arr = [self.userDic objectForKey:key];
    DAUserFileModel *model = [arr objectAtIndex:indexPath.row];
    NSLog(@"MODEL %@",model.filefolderName);
    //文件保存路径
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSLog(@"文件保存路径 %@",documentsDirectory);
    
    //文件下载路径
    NSString *str = model.fileUrl;
    NSString *encodedString = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes( kCFAllocatorDefault, (CFStringRef)str, NULL, NULL,  kCFStringEncodingUTF8 ));
    NSURL *url = [NSURL URLWithString:encodedString];
   // NSURL *url= [NSURL URLWithString:[NSString stringWithFormat:@"http://10.2.8.224/DAKnowledgeUpload/uploads/Tset20160805031214/Tset.pdf"]];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    NSString  *fullPath = [NSString stringWithFormat:@"%@/%@.%@", documentsDirectory, model.filefolderName,model.fileExtend];
    // NSURL *url = [NSURL URLWithString:@"http://www.abc.com/test.mp4"];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    NSURLSessionDownloadTask *task =
    //    [manager downloadTaskWithRequest:request
    //                            progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
    //                                return [NSURL fileURLWithPath:fullPath];
    //                            }
    //                   completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
    //
    //                   }];
    
    [manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
        
        CGFloat count = 1.0 * downloadProgress.completedUnitCount / downloadProgress.totalUnitCount;
        dispatch_async(dispatch_get_main_queue(), ^{
            [cell.progress setProgress:count animated:YES];
        });
      //  NSLog(@"下载进度 %f",count);
        //    if (self.isFinish == NO) {
        //            [SVProgressHUD  showProgress:count];
        //        }
        
    } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
        return [NSURL fileURLWithPath:fullPath];
    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
        cell.progress.hidden = YES;
        cell.downLoadCompleteImage.image = [UIImage imageNamed:@"complete@3x"];
        model.isDownloading = NO;
        //[SVProgressHUD dismiss];
        // [self creatPreview];
    }];
    [task resume];
}

#pragma mark - 解决UISearchDisplayController searchResultsTableView 的ContentSize bug
- (void)searchDisplayController:(UISearchDisplayController *)controller willShowSearchResultsTableView:(UITableView *)tableView{
    [tableView setContentInset:UIEdgeInsetsZero];
    [tableView setScrollIndicatorInsets:UIEdgeInsetsZero];
}


#pragma mark - 判断沙盒里是否有这个文件
-(BOOL)isFileExist:(NSString *)fileName inPath:(NSString *)path{
    NSString *filePath = [path stringByAppendingPathComponent:fileName];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL result = [fileManager fileExistsAtPath:filePath];
  //  NSLog(@"该文件：%@",result?@"有！！":@"不存在");
    return result;
}

- (void)viewWillDisappear:(BOOL)animated{
     [[NSNotificationCenter defaultCenter] postNotificationName:@"REFRESH" object:self];
}

#pragma mark - 用户上传文件数据保存到本地
- (void)archiveToLocalWithData:(NSDictionary *)data{
    // 创建文件夹路径
    NSString *path = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingString:[NSString stringWithFormat:@"%@UploadFile",self.ID]];
    // filePath = path;
    BOOL isSuccess = [data writeToFile:path atomically:YES];
    NSLog(@"用户数据 保存 :%@",path);
    if (isSuccess) {
        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
        [userDefaults setBool:YES forKey:@"isLocalFileData"];
    }
}

#pragma mark - 从本地取出数据
- (NSArray *)getLocalDataWithPath:(NSString *)path{
    NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithContentsOfFile:path];
    //DAUserFileModel *userfileModel = [[DAUserFileModel alloc]init];
   //NSMutableArray *array = [userfileModel returnModelInArrayWithDic:dic[@"result"]];
    DAUserFileModel *userFileModel = [[DAUserFileModel alloc]init];
    NSArray *array = [userFileModel returnModelInArrayWithDic:dic[@"result"]];
    return array;
}
//#pragma mark - FileLisetCell 下载文件
//- (void)downLoadFile:(NSString *)fileName saveInPath:(NSString *)path fromURL:(NSURL *)url{
//    
//    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
//    NSString  *fullPath = [NSString stringWithFormat:@"%@/%@", path, fileName];
//    // NSURL *url = [NSURL URLWithString:@"http://www.abc.com/test.mp4"];
//    NSURLRequest *request = [NSURLRequest requestWithURL:url];
//    NSURLSessionDownloadTask *task =
//    //    [manager downloadTaskWithRequest:request
//    //                            progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
//    //                                return [NSURL fileURLWithPath:fullPath];
//    //                            }
//    //                   completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
//    //
//    //                   }];
//    
//    [manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
//        
//        CGFloat count = 1.0 * downloadProgress.completedUnitCount / downloadProgress.totalUnitCount;
//        //[self.tempCell.progress setProgress:count animated:YES];
//         NSLog(@"下载进度 %f",count);
//   //    if (self.isFinish == NO) {
////            [SVProgressHUD  showProgress:count];
////        }
//
//    } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
//        return [NSURL fileURLWithPath:fullPath];
//    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
//        self.tempCell.progress.hidden = YES;
//        //[SVProgressHUD dismiss];
//       // [self creatPreview];
//        
//        
//    }];
//    [task resume];
//}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
